package com.top10.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.top10.bean.JwtUtil;
import com.top10.bean.ResponseBean;
import com.top10.cache.RedisUtil;
import com.top10.common.DatabaseConst;
import com.top10.common.RedisConst;
import com.top10.common.WebConst;
import com.top10.entity.Admin;
import com.top10.entity.BlackList;
import com.top10.entity.User;
import com.top10.entity.UserOpenid;
import com.top10.entity.vo.AdminVo;
import com.top10.service.IUserOpenidService;
import com.top10.service.IUserService;
import com.top10.service.impl.AdminServiceImpl;
import com.top10.service.impl.BlackListServiceImpl;
import com.top10.utils.GetUuid;
import com.top10.utils.MD5;
import com.top10.utils.RandomUtils;
import com.top10.utils.YunPianVerifyCode;
import io.jsonwebtoken.SignatureAlgorithm;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.top10.utils.SunMd5.md5;


/**
 * 登录和注册Controller
 */
@RestController
@RequestMapping("/function")
public class FunctionController {

    @Value("${jwt.period}")
    private Long period;//token有效时间（毫秒）
    @Value(("${jwt.issuer}"))
    private String issuer;//jwt token 签发人

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AdminServiceImpl adminService;
    @Autowired
    private BlackListServiceImpl blackListService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IUserOpenidService iUserOpenidService;

    @RequestMapping(value = "phone/verifycode", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean sendPhoneVerifyCode(String phoneNumber, String CODE,String account) throws Exception {
        if (CODE == null || CODE.equals("")) {
            return ResponseBean.createError("参数为空");
        }
        if (phoneNumber == null || phoneNumber.equals("")) {
            return ResponseBean.createError("手机格式不合法");
        }
        User user =iUserService.selectOne(new EntityWrapper<User>().eq("account",account));
        if (!phoneNumber.equals(user.getCellphone())){
            return ResponseBean.createError("输入的手机号码跟注册时不一样");
        }

        redisUtil.delete(RedisConst.CODE + CODE);
        Object object = redisUtil.get(RedisConst.CODE + CODE);
        if (object != null) {
            return ResponseBean.createError("重复获取验证码");
        }
        String code = String.valueOf((int) (Math.random() * 1000000));//6位验证码
        // 发送验证码
        //apikey写死在代码里，放配置文件中不安全
        String restJson = YunPianVerifyCode.sendSms("9b7daf334f173ffeaeecf905936190df",
                "【顶十科技】您的验证码是" + code,
                phoneNumber);
        // 返回失败
        String restCode = JSONObject.fromObject(restJson).getString("code");
        if (!restCode.equals("0")) {
            return ResponseBean.createError("发送失败，code: " + restCode);
        }
        redisUtil.set(RedisConst.ACCOUNT, phoneNumber);
        redisUtil.set(RedisConst.CODE + CODE, code);
        return ResponseBean.createSuccess().addData("code", code);
    }


    @RequestMapping(value = "account/register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean Register(AdminVo admin, String CODE) throws Exception {
        if (CODE == null || CODE.equals("")) {
            return ResponseBean.createError("参数为空");
        }
        BlackList blackList = new BlackList();
        blackList.setBlack_value(admin.getPhoneNumber());
        Integer rest1 = blackListService.selectBlackList(blackList.getBlack_value());
        if (rest1 != 0) {
            return ResponseBean.createError("账号可能为黑名单");
        }
        if (!admin.getCode().equals(redisUtil.get(RedisConst.CODE + CODE))) {
            return ResponseBean.createError("验证码输入错误");
        }
        String uuid = adminService.getAdmin(admin.getPhoneNumber());
        if (uuid != null) {

        }

        User user1 = iUserService.getUser(admin.getPhoneNumber());
        if (user1 == null) {
            User user = new User();
            user.setUuid(new GetUuid().newId());
            user.setAccount(admin.getPhoneNumber());

            //保存用户的手机号码
            user.setCellphone(admin.getPhoneNumber());
            user.setPassword(MD5.create(admin.getPassword()));
            user.setNickname("");
            user.setCellphone("");
            user.setStatus(false);
            user.setSex(false);
            user.setType(1);
            user.setHeadSculpture("");
            user.setIsdeleted(false);
            user.setCreatetime(new Date());
            iUserService.insertOne(user);
        } else {
            return ResponseBean.createError("该用户已被注册过了");
        }

        User user2 = iUserService.getUser(admin.getPhoneNumber());
        Admin admin1 = new Admin();
        admin1.setAccount(admin.getPhoneNumber());
        admin1.setPassword(MD5.create(admin.getPassword()));
        admin1.setUuid(user2.getUuid());
        admin1.setCreatetime(new Date());
        admin1.setCreator(admin1.getUuid());
        admin1.setIsdeleted(DatabaseConst.IS_DELETED_NO);
        Integer rest = adminService.insert(admin1);
        if (rest != 0) {
            return ResponseBean.createSuccess().setMessage("注册成功").addData("admin", admin1);
        } else {
            return ResponseBean.createError("注册失败");
        }
    }

    @RequestMapping(value = "/manager/account/update", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean update(AdminVo admin, String CODE,HttpServletRequest request) {
        String userUuid = JwtUtil.getUuidByToken(request);
        if(userUuid==null){
            return ResponseBean.createError("发生错误");
        }


        User user = iUserService.selectOne(new EntityWrapper<User>().eq("uuid", userUuid));
        if (user == null) {
            return ResponseBean.createError("用户名或手机号码错误");
        }

        if (CODE == null || CODE.equals("")) {
            return ResponseBean.createError("参数为空");
        }
        if (!admin.getCode().equals(redisUtil.get(RedisConst.CODE + CODE))) {
            return ResponseBean.createError("验证码输入错误");
        }
     //   User user = new User();
       // user.setAccount(admin.getPhoneNumber());
        user.setPassword(md5(admin.getPassword()));
        iUserService.updateById(user);
        redisUtil.delete(RedisConst.CODE + CODE);
        return ResponseBean.createSuccess();

//        Admin admin1 = new Admin();
//        admin1.setAccount(admin.getPhoneNumber());
//        admin1.setPassword(user.getPassword());
//        admin1.setIsdeleted(DatabaseConst.IS_DELETED_NO);
//        Integer rest2 = adminService.update(admin1);
//        redisUtil.delete(RedisConst.CODE + CODE);
//        if (rest2 != 0) {
//            return ResponseBean.createSuccess().setMessage("更新密码成功");
//        } else {
//            return ResponseBean.createError("更新密码失败");
//        }
    }

    @RequestMapping(value = "account/loginn", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean Loginn(AdminVo admin, HttpServletResponse response, String CODE) throws Exception {
        if (CODE == null || CODE.equals("")) {
            return ResponseBean.createError("参数为空");
        }
        if (!admin.getCode().equals(redisUtil.get(RedisConst.CODE + CODE))) {
            return ResponseBean.createError("验证码输入错误");
        }
        User user = iUserService.selectOne(new EntityWrapper<User>().eq("account", admin.getPhoneNumber()));
        if (user == null) {
            return ResponseBean.createError("该用户不存在，登录失败");
        }
        String uuid = user.getUuid();
        // 制作JWT Token
        String jwtToken = jwtUtil.issueJWT(MD5.getRandomString(20),//令牌id
                uuid,//用户id
                (issuer == null ? JwtUtil.DEFAULT_ISSUER : issuer),//签发
                (period == null ? JwtUtil.DEFAULT_PERIOD : period),//token有效时间
                SignatureAlgorithm.HS512);
        //token存入 response里的Header
        response.setHeader(WebConst.TOKEN, jwtToken);
        redisUtil.delete(RedisConst.CODE + CODE);
        return ResponseBean.createSuccess().setMessage("登录成功").addData("token", jwtToken).addData("uuid", uuid).addData("account",user.getAccount());
    }

    @RequestMapping(value = "account/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean Login(AdminVo adminVo, HttpServletResponse response) throws Exception {
//        if (CODE == null || CODE.equals("")) {
//            return ResponseBean.createError("参数为空");
//        }
        User user = iUserService.selectOne(new EntityWrapper<User>().eq("account", adminVo.getPhoneNumber()));
        if (user == null) {
            return ResponseBean.createError("该用户不存在，登录失败");
        }
        String uuid = user.getUuid();
        String password = user.getPassword();
        if (!password.equals(md5(adminVo.getPassword()))) {
            return ResponseBean.createError("你输入的密码不对");
        }

        // 制作JWT Token
        String jwtToken = jwtUtil.issueJWT(MD5.getRandomString(20),//令牌id
                uuid,//用户id
                (issuer == null ? JwtUtil.DEFAULT_ISSUER : issuer),//签发
                (period == null ? JwtUtil.DEFAULT_PERIOD : period),//token有效时间
                SignatureAlgorithm.HS512);
        //token存入 response里的Header
        response.setHeader(WebConst.TOKEN, jwtToken);
      //  redisUtil.delete(RedisConst.CODE + CODE);
        return ResponseBean.createSuccess().setMessage("登录成功").addData("token", jwtToken).addData("uuid", uuid).addData("account",user.getAccount());
    }

    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean updatePassword(String accountName, String phoneNumber, String passWord, String code1, String code2) {

        if (passWord == null || "".equals(passWord)) {
            return ResponseBean.createError("密码不能为空");

        }
        if (code1 == null || code1.equals("")) {
            return ResponseBean.createError("参数为空");
        }
        if (!code1.equals(redisUtil.get(RedisConst.CODE + code2))) {
            return ResponseBean.createError("验证码输入错误");
        }

        User user = iUserService.selectOne(new EntityWrapper<User>().eq("account", accountName).eq("cellphone", phoneNumber));
        if (user == null) {
            return ResponseBean.createError("用户名或手机号码错误");
        }

        user.setPassword(md5(passWord));
        user.setUpdatetime(new Date());
        iUserService.updateById(user);
        return ResponseBean.createSuccess("密码修改成功");


    }


    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBean Register(String account, String phoneNumber, String password1, String password2,@RequestParam(value="openid",required = false)String openid,@RequestParam(value = "sortid",required = false) Integer sortid) {

        if (account == null || "".equals(account)) {
            return ResponseBean.createError("账号名不能为空");

        }

        if (password1 == null || "".equals(password1)) {
            return ResponseBean.createError("密码不能为空");

        }
        if (password2 == null || "".equals(password2)) {
            return ResponseBean.createError("确认密码不能为空");

        }

        if(!password1.equals(password2)){
            return ResponseBean.createError("密码和确认密码不一样");
        }

        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
        if (phoneNumber.length() != 11) {
            ResponseBean.createError("手机号应为11位数");
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phoneNumber);
            boolean isMatch = m.matches();
            if (!isMatch) {

                ResponseBean.createError("手机格式错误");
            }
        }

        User user1=iUserService.selectOne(new EntityWrapper<User>().eq("account",account));
        if(user1!=null){
            return ResponseBean.createError("该用户名已被占用");
        }

        User user2=iUserService.selectOne(new EntityWrapper<User>().eq("cellphone",phoneNumber));
        if(user2!=null){
            return ResponseBean.createError("该手机号码已被占用");
        }
        User user = new User();
        user.setAccount(account);
        user.setCellphone(phoneNumber);
        user.setNickname(account);
        user.setPassword(md5(password1));
        user.setSex(true);
        user.setHeadSculpture("/head/default.png");
        user.setCreatetime(new Date());

        //1是微信登录,2是QQ登录
        if(openid!=null){
            if (sortid==1){
                UserOpenid userOpenid=iUserOpenidService.selectOne(new EntityWrapper<UserOpenid>().eq("wx_openid",openid));
                user.setUuid(userOpenid.getUserUuid());
            }
            if (sortid==2){
                UserOpenid userOpenid=iUserOpenidService.selectOne(new EntityWrapper<UserOpenid>().eq("qq_openid",openid));
                user.setUuid(userOpenid.getUserUuid());
            }

        }

        user.setUuid(RandomUtils.makeUUID());
        iUserService.insert(user);
        return ResponseBean.createSuccess("注册成功");


    }



}


